package com.zjm.zdk.pl;

public class Pipeline {
    HandlerChainContext head = new HandlerChainContext(new AbstractHandler() {
        @Override
        void doHandler(HandlerChainContext handlerChainContext, Object arg0) {
            handlerChainContext.runNext(arg0);
        }
    });
    void processReq(Object arg0) {
        this.head.handler(arg0);
    }
    void addLast(AbstractHandler handler) {
        HandlerChainContext context = head;
        while (context.next != null) {
            context = context.next;
        }
        context.next = new HandlerChainContext(handler);
    }

    public static void main(String[] args) {
        Pipeline pipeline = new Pipeline();
        pipeline.addLast(new Handler2());
        pipeline.addLast(new Handler1());
        pipeline.addLast(new Handler1());
        pipeline.addLast(new Handler2());
        pipeline.processReq("小火车呜呜呜");
    }
}

class HandlerChainContext {
    public HandlerChainContext(AbstractHandler handler) {
        this.handler = handler;
    }
    HandlerChainContext next;
    private AbstractHandler handler;
    void handler(Object arg0) {
        this.handler.doHandler(this, arg0);
    }
    void runNext(Object arg0) {
        if (this.next != null) {
            this.next.handler(arg0);
        }
    }
}

abstract class AbstractHandler{
    abstract void doHandler(HandlerChainContext handlerChainContext, Object arg0);
}

class Handler1 extends AbstractHandler{
    @Override
    void doHandler(HandlerChainContext handlerChainContext, Object arg0) {
        arg0 = arg0.toString() + "handler1...";
        System.out.println("Handler1 processed..." + arg0);
        handlerChainContext.runNext(arg0);
    }
}

class Handler2 extends AbstractHandler{
    @Override
    void doHandler(HandlerChainContext handlerChainContext, Object arg0) {
        arg0 = arg0.toString() + "handler2...";
        System.out.println("Handler2 processed..." + arg0);
        handlerChainContext.runNext(arg0);
    }
}